#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <pthread.h>

void* client_rec(void* arg);
typedef struct sockaddr* sockaddrp;

int sockfd ;
char name[20];

int main(int argc,char* argv[])
{
	 sockfd = socket(AF_INET,SOCK_STREAM,0);
	
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}
	struct sockaddr_in addr = {AF_INET};
	addr.sin_port = htons(atoi(argv[1]));
	addr.sin_addr.s_addr = inet_addr(argv[2]);

	int ret = connect(sockfd,(sockaddrp)&addr,sizeof(addr));
	if(0 > ret)
	{
		perror("connect");
		return -1;
	}
	
	
	printf("请输入你的昵称:\n");
	gets(name);
	pthread_t tid;

	pthread_create(&tid,NULL,client_rec,NULL);
	char buf[255];
	sprintf(buf,"%s进入聊天室",name);
	int p = send(sockfd,buf,strlen(buf),0);
	if(p<0)
	{
		perror("send");
		return -1;
	}
	while(1)
	{
		char buf1[255] = {};
		gets(buf1);
		char msg[255] = {};
		if(0 == strcmp("q",buf1))
		{
			sprintf(msg,"%s已经退出",name);
			send(sockfd,msg,strlen(msg),0);
			break;
		}
		sprintf(msg,"%s:%s",name,buf1);
		send(sockfd,msg,strlen(msg),0);
	}
		close(sockfd);
}

void* client_rec(void* arg)
{
	
	while(1)
	{
		char buf[255] = {};
		int ret = recv(sockfd,buf,sizeof(buf),0);
		if(ret == 0)
		{
			printf("%s\n",buf);
		}
		if(ret < 0)
		{
			perror("recv");
			return NULL;
		}

	}
}


